//
//  LoginViewModel.swift
//  GomroBoss
//
//  Created by apple on 2020/2/10.
//  Copyright © 2020 cn.gomro.app. All rights reserved.
//

import Foundation

/** LoginViewModel  */
class LoginViewModel: BaseViewModel {
    
    lazy var isSelected:Bool = false
    
    
    //MARK: - 登录
    private func loginAction(strName:String?,
                             strPwd:String?,
                             andRacSubscriber subscriber:RACSubscriber? = nil) {
        guard let uname:String = strName,!uname.isEmpty else{
            SVProgressHUD.showInfo(withStatus:"请输入账号")
            subscriber?.sendCompleted()
            return
        }
        
        guard let upwd:String = strPwd,!upwd.isEmpty else{
            SVProgressHUD.showInfo(withStatus:"请输入密码")
            subscriber?.sendCompleted()
            return
        }
        
        CMRequest.shareInstance().oAuthRequestPasswordFor(Username: uname,
                                             andPwd: upwd,
                                             andSuccessBack: {[weak self] (responseData:Any?) -> (Void) in
                                                guard let self = self,let access_token = responseData as? String else { return }
                                                
                                                print("access_token:\(access_token)")
                                                
                                                subscriber?.sendCompleted()
                                                
                                                UserModel.userTooken = access_token
                                                self.queuGroupNotify(access_token: access_token,
                                                                     andUid: uname,
                                                                     withPwd: upwd)
            }, andFailureBack: {( strError:String?) -> (Void) in
                print("access_token:\(strError ?? "请求异常")")
    
                SVProgressHUD.showInfo(withStatus: strError)
                subscriber?.sendCompleted()
        }, withisLoading: true)
    }
    
    /** 线程组执行完毕通知 */
    private func queuGroupNotify(access_token:String,
                                 andUid uid:String,
                                 withPwd pwd:String){
        
        SVProgressHUD.showLoading()
        
        var rongCloudToken:String?
        var userDic:[String:Any]?
        let gcdGroup = DispatchGroup.init()
        
        gcdGroup.enter()
        let rctQueue = DispatchQueue.init(label: "rongCloudToken")
        rctQueue.async(group: gcdGroup, qos: .default, flags: []) {
            self.getRongCloudTokenFor(AccessToken: access_token,
                                      andGroupQueue: gcdGroup) { (rt:String?) -> (Void) in
                                        rongCloudToken = rt
            }
        }
        
        //获取用户信息
        gcdGroup.enter()
        let udQueue = DispatchQueue.init(label: "getUserData")
        udQueue.async(group: gcdGroup, qos: .default, flags: []) {
            self.getUserDataFot(AccessToken: access_token,
                                andGroupQueue: gcdGroup) { (ud:[String : Any]?) -> (Void) in
                userDic = ud
            }
        }
        
        //记住密码
        gcdGroup.enter()
        let keeppwd = DispatchQueue.init(label: "keepPassword")
        keeppwd.async(group: gcdGroup, qos: .default, flags: []) {
            let result:Bool = FMDBUtils.shareInstance.keepPasswordFor(User: uid, andPwd: pwd,withRemember: self.isSelected)
            print("\(self.isSelected ? "记住" : "保存")密码:\(result ? "成功":"失败")")
            gcdGroup.leave()
        }
        
        gcdGroup.notify(queue: DispatchQueue.main) {
            print("GroupQueue notify")
            SVProgressHUD.dismissLoading()
            
            if userDic != nil {
                
                guard let strOrgTypeName:String = userDic?["authorities"].map({ return "\($0)" }) ?? "",strOrgTypeName.contains("PM") else {
                    SVProgressHUD.showInfo(withStatus: "只支持驻场账号登录")
                    
                    self.loginFinishSubject.sendCompleted()
                    return
                }
                
                SVProgressHUD.showSuccess(withStatus: "登录成功")
                
                //保存用户数据
                DispatchQueue.main.async {
                    UserModel.userIsLogined = true
                    if rongCloudToken != nil {
                        UserModel.userRongCloudToken = rongCloudToken
                    }
                    UserModel.userDicData = userDic
                    
                    //进入主程序
                    AppDelegate.app().enterMainApp()
                }
                
                //登录完成回调
                self.loginFinishSubject.sendNext(true)
                self.loginFinishSubject.sendCompleted()
            }
            else{
                SVProgressHUD.showInfo(withStatus: "登录失败，请稍后再试")
                self.loginFinishSubject.sendCompleted()
            }
        }
    }
    
    
    //获取融云token
    private func getRongCloudTokenFor(AccessToken at:String,
                                      andGroupQueue gq:DispatchGroup,
                                      andRongTokenBlock rtb:@escaping((_ rt:String?)->(Void))){
        
        let strUrl = String.init(format:"%@login/token",K_APP_REQUEST_HOST)
        CMRequest.shareInstance().getRequestForServerData(strUrl: strUrl,
                                withParameters: [UserModel.k_user_tooken:at as Any],
                                AndSuccessBack: {(responseData:Any?) in
                                    gq.leave()
                                    
                                    if let _dic:[String:Any] = responseData as? [String:Any] {
                                        let rt = _dic[UserModel.k_user_rong_cloud_token] as? String
                                        print("rongCloudToken:\(rt ?? "rongCloudToken error")")
                                        rtb(rt)
                                    }
        },
                                AndFailureBack: { (strError:String?) in
                                    gq.leave()

                                    print(strError ?? "login/token 请求异常")
                                    //SVProgressHUD.showInfo(withStatus: strError)
        },
                                WithisLoading: false)
    }
    
    /** 获取登录信息 */
    private func getUserDataFot(AccessToken at:String,
                                andGroupQueue gq:DispatchGroup,
                                andUserDataBlock udb:@escaping((_ ud:[String:Any]?)->(Void))){
        
        let strUrl = String.init(format:"%@user",K_APP_REQUEST_HOST).replacingOccurrences(of: "v2/", with: "")
        CMRequest.shareInstance().getRequestForServerData(strUrl: strUrl,
                                withParameters: [UserModel.k_user_tooken:at as Any],
                                AndSuccessBack: {(responseData:Any?) in
                                    gq.leave()
                                    
                                    if let _dic:[String:Any] = responseData as? [String:Any] {
                                     print("MemberByToken:\(_dic)")
                                    
                                     if _dic.keys.contains("details") {
                                        let _dicTemp = (_dic["details"] as? [String:Any])?["principal"] as? [String:Any]
                                        udb(_dicTemp)
                                    }
                                     else{
                                        udb(_dic)
                                    }
                                }
        },
                                AndFailureBack: { (strError:String?) in
                                    gq.leave()
                                    
                                    print("MemberByToken :\(strError ?? "请求异常")")
                                    SVProgressHUD.showInfo(withStatus: strError)
        },
                                WithisLoading: false)
    }
    
    
    //MARK: - lazy load
    /** 登录 */
    lazy var loginInCommand:RACCommand = {
        let _comm = RACCommand.init {[weak self] (input:Any?) -> RACSignal? in
            guard let self = self else { return nil}
            
            let signal:RACSignal = RACSignal.createSignal {[weak self] (subscriber:RACSubscriber?) -> RACDisposable? in
                guard let self = self else { return nil }
                guard let arrTemp:[String] = input as? [String],arrTemp.count > 1 else { return nil }
                
                self.loginAction(strName:arrTemp.first,
                                 strPwd:arrTemp.last,
                                 andRacSubscriber:subscriber)
                return nil
            }
            
            return signal
        }
        
        return _comm!
    }()
    
    /** 忘记密码 */
    lazy var forgetPwdSubject:RACSubject = {
        return RACSubject.init()
    }()
    
    /** 登录完成 */
    lazy var loginFinishSubject:RACSubject = {
        return RACSubject.init()
    }()
}
